package com.log;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.PropertyConfigurator;

public class InitLog4jServlet extends HttpServlet {

    /**
	 * 
	 */
	private static final long serialVersionUID = -6532070200387801658L;
	private String propertyConfig="/WEB-INF/classes/log4j.properties";
	@Override
	public void init() throws ServletException {
		super.init();
		
		String file=getInitParameter(propertyConfig);
		if(file!=null&&!file.equals("")){
			propertyConfig=file.trim();
		}
		URL fileURL=null;
		try {
			fileURL=getServletContext().getResource(propertyConfig);//加载配置文件
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		if(fileURL==null){
			fileURL=getClass().getResource(propertyConfig);//加载配置文件
		}else if(fileURL==null){
			fileURL=getClass().getClassLoader().getResource(propertyConfig);//得到当前类的类装载器,在WEB-INF/classes下加载配置文件
		}else if(fileURL==null){
		  throw new ServletException("无法找到“log4j.properties”配置文件。"); 	
		}
		PropertyConfigurator.configure(fileURL);
		
	}

}








